package com.fzf.blog.modules.api.controller;

import com.fzf.blog.core.util.IpUtil;
import com.fzf.blog.core.util.JsonUtil;
import com.fzf.blog.core.util.ReType;
import com.fzf.blog.modules.admin.model.Blog;
import com.fzf.blog.modules.admin.service.BlogService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * 文章查询
 *
 * @author fzf
 * @date 2019-10-05
 */
@RestController
@RequestMapping("/blog")
public class ApiBlogController {

    @Autowired
    private BlogService blogService;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    /**
     * 获取 文章列表
     *
     * @param searchWord
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ReType getList(String searchWord, Integer page, Integer limit) {
        if (null != searchWord && !"".equals(searchWord)) {
            return blogService.selectBySearchWord(searchWord,page,limit);
        }else{
            return blogService.selectAll(page,limit);
        }
    }
    
    
    /**
     * 根据code获取文章内容
     *
     * @param code
     * @return
     */
    @GetMapping("/getDetail/{code}")
    public JsonUtil detail(@PathVariable("code") Integer code, HttpServletRequest request) {
        String ip = IpUtil.getIp(request);
        return blogService.detail(code, ip);
    }
    
    
    /**
     * 获取阅读排行榜
     *
     * @return
     */
    @GetMapping("/read/order")
    public ReType getArticleByReadNumber() {
    	 PageHelper.startPage(1, 5);  	 
    	 List<Blog> blogs =blogService.getArticleByReadNumber();
        ReType reType = new ReType();
        reType.setData(blogs);
        return reType;
    }
    
    
    /**
     * 获取推荐排行榜
     *
     * @return
     */
    @GetMapping("/recommended")
    public ReType getBlogByRecommended() {
    	 PageHelper.startPage(1, 3);  	 
    	 List<Blog> blogs =blogService.getArticleByRecommended();
    	 blogs.forEach(s -> {
             s.setContent(null);
         });    	 
        ReType reType = new ReType();
        reType.setData(blogs);
        return reType;
    }
}
